<template>
  <Dialog :appDialog="appDialog">
    <div class="label_con">
      <el-radio-group v-if="batchTag" v-model="RadioTags.defaultVal" class="radio_list">
        <el-radio
          v-for="item in RadioTags.seleTagOp"
          :key="item.value"
          :label="item.value"
          class="radio_list_item"
        >
          <span class="radio_list_item_text">{{ item.name }}</span>
          <el-tooltip :content="item.text" placement="bottom" effect="light">
            <div class="radio_list_item_icon radio_img">
              <img src="@/assets/image/material/question.png" alt="" />
            </div>
          </el-tooltip>
        </el-radio>
      </el-radio-group>
      <template v-if="labelList.length > 0">
        <el-scrollbar max-height="400px">
          <el-scrollbar class="label_box" max-height="80px">
            <div
              v-for="k in labelList"
              :key="k.id"
              :class="{ tag_item: true, pad_4_10: true, tag_item_active: k.selted }"
              type="info"
              @click="k.selted = !k.selted"
              effect="plain"
            >
              {{ k.name }}
            </div>
          </el-scrollbar>
        </el-scrollbar>
      </template>
      <template v-else>
        <div class="no_data">
          <img class="no_img" src="@/assets/noData.png" alt="" />
          <div class="no_title">暂无数据</div>
        </div>
      </template>
      <div v-if="showCreatTag" class="new_group">
        <!-- <div class="label_title">
          新建分组：
          <el-switch v-model="isGroup" />
        </div> -->
        <el-form
          ref="formRef"
          v-if="isGroup"
          :model="groupData"
          label-width="100px"
          class="demo_dynamic"
        >
          <el-form-item
            prop="name"
            label="分组名称："
            :rules="[
              {
                required: true,
                message: '分组名称不能为空',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              class="group_data_name"
              v-model="groupData.name"
              maxlength="15"
            ></el-input>
          </el-form-item>
          <el-form-item
            prop="tags"
            label="标签："
            :rules="[
              {
                required: true,
                message: '标签不能为空',
                trigger: 'blur',
              },
            ]"
          >
            <el-tag
              v-for="tag in groupData.tags"
              :key="tag"
              class="tag_item"
              type="warning"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="inputVisible"
              ref="InputRef"
              v-model="inputValue"
              class="create_label_input"
              maxlength="15"
              placeholder="请输入标签内容"
              @keyup.enter="handleInputConfirm"
              @blur="handleInputConfirm"
            >
            </el-input>
            <!-- <el-button v-else plan class="button-new-tag ml-1" @click="createLabel"
              >新建标签</el-button
            > -->
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="saveLabel">保存新建标签</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </Dialog>
</template>
<script setup lang="ts">
import Dialog from "./Dialog.vue";
import { ref, reactive, toRefs, nextTick, watchEffect, computed, watch } from "vue";
import bus from "@/utils/bus";
import { ElInput, ElForm, ElMessage } from "element-plus";
import { addTags, batchTagAdd, batchTagDel, editTextTag } from "@/api/common";
import { getTagsList } from "@/api/customerCenter";
import { getSetionId } from "@/utils/utils";
const InputRef = ref<InstanceType<typeof ElInput>>();
const formRef = ref<InstanceType<typeof ElForm>>();

import { useStore } from "@/store";
const store = useStore();

const emit = defineEmits(["submit"]);
const props = defineProps(["formTags"]);
//是否编辑标签
const textEdit = ref(false);
const showCreatTag = ref(false);
// 添加标签
const batchTag = ref(false);
// 批量处理标签
const TagsVis = ref(false);
// 选中标签
const selectTags = ref([]);

// 标签标题
const tagsTitle = ref("选择标签");

const type = computed(() => {
  return store.getters["content/type"];
});
const tagsInfo = computed(() => {
  return store.getters["content/tagsInfo"];
});
// 选中复选框
const table = computed(() => {
  return store.getters["table"];
});
// 选择ID
const sectionIds = ref([]);
// 是否全选
const sectionAll = ref(false);

const labelList = ref([]);

const RadioTags = reactive({
  defaultVal: 0,
  seleTagOp: [
    {
      name: "批量打标签",
      value: 0,
      text: "若内容本身已有所选标签，则不针对此内容重复打标签",
    },
    {
      name: "批量移除标签",
      value: 1,
      text: "若内容本身没有所选标签，则不针对此内容重复移除标签",
    },
  ],
});
// 获取标签列表
const tagsList = async (tags: any[]) => {
  let arr: any[] = [];
  if (tags && tags.length > 0) {
    tags.forEach((item: any) => {
      arr.push(item.id || item.tag_id);
    });
  }
  let res = await getTagsList();
  labelList.value = res;
  labelList.value.map((item: any) => {
    if (arr.includes(item.id)) {
      item.selted = true;
    } else {
      item.selted = false;
    }
    /*  item.tags.forEach((k: any) => {
      if (arr.includes(k.id)) {
        k.selted = true
      } else {
        k.selted = false
      }
    }) */
  });
};

// 取消
const cancelHandel = () => {
  appDialog.visible = false;
  showCreatTag.value = false;
  formRef.value?.resetFields();
};
const getCheckTag = (data: any) => {
  let arr: any[] = [];
  data.value.forEach((item: any) => {
    if (item.selted) {
      arr.push(item);
    }
    /* if (item.tags && item.tags.length > 0) {
      item.tags.forEach((tag: any) => {
        if (tag.selted) {
          arr.push(tag)
        }
      })
    } */
  });
  selectTags.value = arr;
};
bus.on("change", (data: any) => {
  sectionIds.value = getSetionId("id", data);
});

// 保存
const submitHandel = async () => {
  // 新增标签
  if (isGroup.value) {
    formRef.value.validate((valid: any) => {
      if (!valid) return;
      getCheckTag(labelList);
    });
  } else {
    getCheckTag(labelList);
  }
  // 批量标签
  if (batchTag.value) {
    emit("submit", {
      tag_ids: selectTags.value,
      defaultVal: RadioTags.defaultVal,
    });
  } else {
    emit("submit", selectTags.value);
  }
  appDialog.visible = false;
  appDialog.title = "新建标签";
  showCreatTag.value = false;
  RadioTags.defaultVal = 0;
  batchTag.value = false;
};
const isGroup = ref(false);
// 弹框
const appDialog = reactive({
  visible: false,
  title: "选择标签",
  width: "700px",
  cancel: cancelHandel,
  submit: submitHandel,
  cancelText: "取消",
  submitText: "保存",
});
watchEffect(() => {
  if (appDialog.visible) {
    tagsList(selectTags.value);
  }
});
watch(table, (table) => {
  sectionAll.value = table.tableAll;
  sectionIds.value = getSetionId("id", table.tableData);
});

// 新建分组
const groupData = reactive({
  name: "",
  tags: [],
});
// 新建标签
const inputValue = ref("");
const inputVisible = ref(false);
const handleClose = (tag: string) => {
  const data = groupData.tags.filter((item: string) => item !== tag);
  groupData.tags = data;
};
const createLabel = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};
const handleInputConfirm = () => {
  if (inputValue.value) {
    if (groupData.tags.includes(inputValue.value)) {
      ElMessage.warning("新建标签名不能重复");
      return;
    }
    groupData.tags.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = "";
};
// 保存新建
const saveLabel = () => {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      try {
        const res = await addTags(groupData);
        ElMessage.success("创建标签成功");
        tagsList();
        formRef.value.resetFields();
      } catch (e) {}
    }
  });
};
defineExpose({
  sectionIds,
  textEdit,
  appDialog,
  batchTag,
  selectTags,
  showCreatTag,
  RadioTags,
});
</script>
<style lang="scss" scoped>
.label_con {
  margin-top: 10px;
  .radio_list {
    &_item {
      &_text {
        margin-top: -3px;
      }
      &_icon {
        width: 14px;
        height: 14px;
        margin: -3px 0 0 6px;
        img {
          width: 100%;
          height: 100%;
        }
      }
    }
    :deep .el-radio__label {
      display: flex;
      align-items: center;
    }
  }
  .label_title {
    margin-bottom: 10px;
  }
  .tag_item {
    display: inline-block;
    color: #969696;
    background: #ffffff;
    border: 1px solid #eaeaea;
    margin-right: 16px;
    margin-bottom: 10px;
    cursor: pointer;
    &_active {
      color: #ff6b00;
      border: 1px solid #ff6b00;
    }
  }
  .pad_4_10 {
    padding: 4px 10px;
  }
  .demo_dynamic {
    .group_data_name {
      width: 300px;
    }
    .create_label_input {
      width: 140px;
    }
  }
  .no_data {
    height: 300px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    .no_img {
      margin-left: 35px;
    }
  }
}
</style>
